package com.enhe.gck.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.enhe.gck.CarbonBaseConstant;
import com.enhe.gck.CarbonEnumKeyValue;
import com.enhe.gck.item.WovenBagUseRecordTempHWANE21450Item;
import com.enhe.gck.pojo.WovenBag;
import com.enhe.gck.pojo.WovenBagRecord;
import com.enhe.gck.pojo.WovenBagUseRecordTemp;
import com.kuangkie.carbon.common.IntegrationMsg;
import com.kuangkie.carbon.common.RemoveDTO;
import com.kuangkie.carbon.panel.CarbonPanel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 编织袋记录service
 */
@Slf4j
@Service
@AllArgsConstructor
public class WovenBagRecordService {

    private final WovenBagService wovenBagService;

    public Optional<WovenBagRecord> getWovenBagRecord(Long orderId, String orderNo, int number, long recordType) {
        if (0 == number) {
            log.warn("订单：{}；编织袋变更数量为0，无需保存编织袋记录！", orderNo);
            return Optional.empty();
        }
        // 查找班次
        Optional<WovenBag> wovenBagNowOptional = wovenBagService.getWovenBagNow();
        if (!wovenBagNowOptional.isPresent()) {
            log.warn("当前班次不存在，无法保存编织袋记录！");
            return Optional.empty();
        }

        WovenBagRecord wovenBagRecord = new WovenBagRecord();
        wovenBagRecord.setNumber(number);
        wovenBagRecord.setIsConfirm(true); // 自动确认
        wovenBagRecord.setType(String.valueOf(recordType));
        wovenBagRecord.setWovenBagId(wovenBagNowOptional.get().getId());
        wovenBagRecord.setOrderId(orderId);
        wovenBagRecord.setIsCancel(false);
        return Optional.of(wovenBagRecord);
    }

    public void save(Long orderId, String orderNo, int number, long recordType) {
        Optional<WovenBagRecord> wovenBagRecordOptional = getWovenBagRecord(orderId, orderNo, number, recordType);
        if (!wovenBagRecordOptional.isPresent()) {
            return;
        }

        IntegrationMsg msg = CarbonPanel.getRecordIntegration(CarbonBaseConstant.编织袋记录_bzdjl).integrate(wovenBagRecordOptional.get());
        if (!msg.success()) {
            log.error("保存编织袋记录失败！订单号：{}；数量：{}；记录类型：{}；原因：{}", orderNo, number, getRecordTypeCH(recordType), msg.getRefuseMsgContentStr());
        } else {
            log.warn("保存编织袋记录成功！订单号：{}；数量：{}；记录类型：{}", orderNo, number, getRecordTypeCH(recordType));
        }
    }

    private String getRecordTypeCH(long recordType) {
        if (CarbonEnumKeyValue.编织袋记录类型_使用_sy == recordType) {
            return "使用";
        } else if (CarbonEnumKeyValue.编织袋记录类型_补包_bb == recordType) {
            return "补包";
        } else if (CarbonEnumKeyValue.编织袋记录类型_退包_tb == recordType) {
            return "退包";
        } else if (CarbonEnumKeyValue.编织袋记录类型_破损_ps == recordType) {
            return "破损";
        } else {
            return "未知";
        }
    }

    public void mergeWovenBagRecord(Long orderId, String orderNo) {
        List<WovenBagUseRecordTemp> wovenBagUseRecordTempList = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.编织袋使用记录临时表_bzdsyjllsb)
                .getProConJunctionFactory()
                .addEqual(WovenBagUseRecordTempHWANE21450Item.基本属性组_订单ID, orderId)
                .goBack()
                .queryBeans(WovenBagUseRecordTemp.class);
        if (CollectionUtil.isEmpty(wovenBagUseRecordTempList)) {
            log.warn("查询到需要合并的订单的编织袋使用记录为空，无需合并！");
            return;
        }

        // 按照订单号和编织袋管理id分组
        Map<Long, Map<Long, Integer>> wovenBagRecordMap = wovenBagUseRecordTempList.stream()
                .collect(Collectors.groupingBy(
                        WovenBagUseRecordTemp::getOrderId,
                        Collectors.groupingBy(
                                WovenBagUseRecordTemp::getWovenBagId,
                                Collectors.summingInt(WovenBagUseRecordTemp::getNumber)
                        )));

        List<WovenBagRecord> wovenBagRecords = wovenBagRecordMap.entrySet().stream()
                .flatMap(e -> e.getValue().entrySet().stream()
                        .map(sub -> {
                            WovenBagRecord wovenBagRecord = new WovenBagRecord();
                            wovenBagRecord.setNumber(sub.getValue());
                            wovenBagRecord.setIsConfirm(true);
                            wovenBagRecord.setType(String.valueOf(CarbonEnumKeyValue.编织袋记录类型_使用_sy));
                            wovenBagRecord.setConfirmTime(LocalDateTime.now());
                            wovenBagRecord.setIsCancel(false);
                            wovenBagRecord.setWovenBagId(sub.getKey());
                            wovenBagRecord.setOrderId(e.getKey());
                            return wovenBagRecord;
                        })
                ).collect(Collectors.toList());

        Collection<IntegrationMsg> msgCollection = CarbonPanel.getRecordIntegration(CarbonBaseConstant.编织袋记录_bzdjl).integrate(wovenBagRecords);
        if (CollectionUtil.isNotEmpty(msgCollection) && msgCollection.stream().anyMatch(e -> !e.success())) {
            log.warn("合并订单的编织袋使用记录失败！订单号：{}", orderNo);
            return;
        } else {
            log.warn("合并的订单的编织袋使用记录：{}", JSONUtil.toJsonStr(wovenBagRecords));
        }

        RemoveDTO removeDTO = new RemoveDTO(null, wovenBagUseRecordTempList.stream().map(e -> String.valueOf(e.getId())).collect(Collectors.toList()), "订单的编织袋使用记录（Temp）删除");
        IntegrationMsg msg = CarbonPanel.getRecordIntegration(CarbonBaseConstant.编织袋使用记录临时表_bzdsyjllsb).remove(removeDTO);
        if (!msg.success()) {
            log.error("订单的编织袋使用记录（Temp）删除失败！订单号：{}；原因：{}", orderNo, msg.getRefuseMsgContentStr());
        } else {
            log.warn("订单的编织袋使用记录（Temp）删除成功！订单号：{}", orderNo);
        }
    }
}
